import React, {useCallback, useEffect, useState} from "react"
import {Button, Form, Input, Select, Space, Table} from "antd";
import {DeleteOutlined, PlusOutlined} from "@ant-design/icons";
import {getAllMarket, getAllMarketsOnlyICanSee} from "../../apis/MarketsApi";
import FormDrawer from "../../components/FormDrawer";
import DataPageLayout from "../../components/DataPageLayout";
import AuthorizationResource from "../../components/AuthorizationResource";
import {NumberIdAndName} from "../../types/BasicModels";
import {
    createMarketReturnOrder, deleteMarketReturnOrder,
    getAllMarketReturnOrderCreatedEmployees, MarketReturnOrderStatus, marketReturnOrderStatuses, marketReturnOrderStatusMap,
    QueryMarketReturnOrderResponse,
    queryMarketReturnOrders
} from "../../apis/MarketReturnOrderApi";
import {useNavigate, useSearchParams} from "react-router-dom";
import {Pageable} from "../../utils/Page";
import {mergePaginationAndPageable, useTableFilterDateRangeColumnProps} from "../../utils/AntdTableUtils";
import {LocalDate, OffsetDateTime} from "@js-joda/core";
import {observerDashboardPageWrapper} from "../../components/dashboardPages/ObserverDashboardPageWrapper";
import {Link} from "react-router-dom";
import employeeAuthorizationStore from "../../store/EmployeeAuthorizationStore";
import LoadableButton from "../../components/LoadableButton";
import {useGlobalStyle} from "../../global.style";
import {DATE_WITH_TIME_FORMATER} from "../../utils/Date";

export interface pageProps {

}

export interface MarketReturnOrderFormData {
    marketId: number
    note:string
}


const MarketReturnOrderPage: React.FC<pageProps> = (props) => {
    const [pageable, setPageable] = useState(new Pageable())
    const [data, setData] = useState<QueryMarketReturnOrderResponse[]>([])
    const [loading, setLoading] = useState(false)
    const [totalElements, setTotalElements] = useState(0)
    let [urlSearchParams] = useSearchParams();
    const [marketIds, setMarketIds] = useState<number[]>(urlSearchParams.getAll("marketIds").map(it => parseInt(it)))
    const [createdByIds, setCreatedByIds] = useState<number[]>([])


    const [markets, setMarkets] = useState<Array<NumberIdAndName>>([])
    useEffect(() => {
        getAllMarketsOnlyICanSee().then(response => {
            setMarkets(response.data)
        })
    }, []);

    const [openAddDrawer, setOpenAddDrawer] = useState(false)

    const [startDate, setStartDate] = useState<string>()
    const [endDate, setEndDate] = useState<string>()
    const [status, setStatus] = useState<MarketReturnOrderStatus>()
    const query = useCallback(() => {
        setLoading(true)
        queryMarketReturnOrders({
            marketIds,
            createdByIds: createdByIds,
            startDate: startDate ? LocalDate.parse(startDate).toString() : undefined,
            endDate: endDate ? LocalDate.parse(endDate).toString() : undefined,
            status,
        }, pageable).then(response => {
            setData(response.data.content)
            setTotalElements(response.data.totalElements)
        }).finally(() => {
            setLoading(false)
        })
    }, [...pageable.toDependencyList(), marketIds, createdByIds, startDate, endDate, status])
    useEffect(() => {
        query()
    }, [query]);
    const [createdByEmployees, setCreatedByEmployees] = useState<NumberIdAndName[]>([])
    useEffect(() => {
        getAllMarketReturnOrderCreatedEmployees().then(response => response.data).then(setCreatedByEmployees)
    }, []);

    function buildFormItems() {
        return <>
            <Form.Item label={"卖场"} name="marketId" rules={[{required: true}]}>
                <Select placeholder={"选择卖场"}>
                    {markets.map(market => {
                        return <Select.Option key={market.id} value={market.id}>{market.name}</Select.Option>
                    })}
                </Select>
            </Form.Item>
            <Form.Item label={"备注"} name={"note"}>
                <Input.TextArea/>
            </Form.Item>
        </>
    }

    let navigate = useNavigate();
    let globalStyle = useGlobalStyle();
    return <>
        <DataPageLayout rightActions={<AuthorizationResource authorities={["卖场_退货单_下单"]}>
            <Button type={"primary"} onClick={() => {
                setOpenAddDrawer(true)
            }}><PlusOutlined/>下单</Button>
        </AuthorizationResource>}>
            <Table<QueryMarketReturnOrderResponse> className={globalStyle.rowClickableTable} onRow={item => {
                return {
                    onClick: () => {
                        navigate(`/markets/returnOrders/${item.id}`)
                    }
                }
            }} size={"small"} loading={loading} dataSource={data} rowKey={"id"} pagination={{
                current: pageable.page,
                pageSize: pageable.size,
                total: totalElements,
            }} onChange={(pagination, filters, sorter) => {
                setPageable(mergePaginationAndPageable(pagination, pageable, sorter))
                setMarketIds(filters["market.name"] as number[])
                setCreatedByIds(filters["createdBy.name"] as number[])
                let filter = filters["status"] as unknown as MarketReturnOrderStatus[];
                setStatus(filter?filter[0]:undefined)
            }}>
                <Table.Column<QueryMarketReturnOrderResponse> filteredValue={marketIds} dataIndex={["market", "name"]}
                                                        title={"卖场"}
                                                        filters={markets.map(market => {
                                                            return {
                                                                text: market.name,
                                                                value: market.id,
                                                            }
                                                        })} render={(_, record) => {
                    return record.market.name
                }}/>
                <Table.Column dataIndex={"createdDateTime"} title={"下单时间"}
                              {...useTableFilterDateRangeColumnProps<QueryMarketReturnOrderResponse>("createdDateTime", {
                                  handleSearch:value => {
                                      setStartDate(value?value[0].format():undefined)
                                      setEndDate(value?value[1].format():undefined)
                                  }
                              })}
                              render={(value) => value.format(DATE_WITH_TIME_FORMATER)}/>
                <Table.Column dataIndex={["goodsKindAmount"]} title={"单品数量"}/>
                <Table.Column<QueryMarketReturnOrderResponse> dataIndex={"status"}
                                                        filteredValue={status?[status]:[]}
                                                        title={"状态"}
                                                        key={"status"}
                                                        filterMultiple={false}
                                                        filters={marketReturnOrderStatuses.map(it => ({
                                                            text: marketReturnOrderStatusMap[it],
                                                            value: it
                                                        }))} render={(value, record) => {
                    return marketReturnOrderStatusMap[value]
                }}/>
                <Table.Column dataIndex={["createdBy", "name"]} title={"下单人员"}
                              filters={createdByEmployees.map(it => ({text: it.name, value: it.id}))}/>
                <Table.Column<QueryMarketReturnOrderResponse> title={"操作"} render={(_, record) => {
                    return <>
                        {employeeAuthorizationStore.hasAuthority("卖场_退货单_删除")&&record.status==="WAIT_SUBMIT"&&<LoadableButton danger type={"text"} onClick={async (event) => {
                            event.stopPropagation()
                            await deleteMarketReturnOrder(record.id)
                            query()
                        }}><DeleteOutlined/>删除</LoadableButton>}
                    </>
                }}/>
            </Table>
        </DataPageLayout>
        <FormDrawer<MarketReturnOrderFormData> onClose={() => setOpenAddDrawer(false)}
                                         title={"下单"}
                                         onConfirm={async (values) => {
                                             return createMarketReturnOrder(values.marketId,{
                                                 note:values.note
                                             }).then(response => {
                                                 setOpenAddDrawer(false)
                                                 navigate(`/markets/returnOrders/${response.data}`)
                                                 query()
                                             })
                                         }}
                                         open={openAddDrawer}>
            {buildFormItems()}
        </FormDrawer>
    </>
}
export default observerDashboardPageWrapper(MarketReturnOrderPage, "markets/returnOrders", "卖场退货单")
